﻿using NewLife.RocketMQ;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Intrinsics.X86;
using System.Threading.Tasks;
using IntelligentEscalator.BUS.RocketMQ;
using IntelligentEscalator.DAL;
using IntelligentEscalator.ElevatorWebSocket;
using IntelligentEscalator.Models;
using static IntelligentEscalator.Models.MqttDataInfo;

namespace IntelligentEscalator.BUS
{
    public class ElevatorStateBUS
    {
        //public static Dictionary<string, LiftStateALL> _dic = new Dictionary<string, LiftStateALL>();
        public static List<LiftStateALL> state_list = new List<LiftStateALL>();
        public static List<Elevator> device_list = new List<Elevator>();
        public static List<ElevatorStateRun> run_list = new List<ElevatorStateRun>();
        public static List<ElevatorStateRunTime> runtime_list = new List<ElevatorStateRunTime>();
        public static KoneDeviceStatus KoneDeviceStatus = new KoneDeviceStatus();
        public static int Offline;

        public ElevatorStateBUS()
        {
        }

        public ResponseMessage ProcessData(LiftStateALL liftState, out LiftStateALL outstate)
        {
            ResponseMessage message = new ResponseMessage();
            try
            {
                if (device_list != null)
                {
                    int device_index = device_list.FindIndex(x => x.opcNO == liftState.opcNO);
                    if (device_index > -1)
                    {
                        Elevator elevatorinfo = new Elevator();

                        elevatorinfo = device_list[device_index];
                        if (elevatorinfo != null)
                        {
                            liftState.IPAddress = elevatorinfo.ipAddress;
                            liftState.ElevatorID = elevatorinfo.id;
                            liftState.AreaID = elevatorinfo.areaId;
                            liftState.Areaname = elevatorinfo.areaName;
                            liftState.ElevatorName = elevatorinfo.elevatorName;
                            liftState.ElevatorNO = elevatorinfo.elevatorNO;
                            liftState.Speed = elevatorinfo.speed;
                            liftState.SaleNo = elevatorinfo.saleNo;
                            liftState.ContractNo = elevatorinfo.contractNo;
                            liftState.Outofservice = Convert.ToInt32(elevatorinfo.outofservice);
                            liftState.Model = elevatorinfo.model;
                            liftState.Manufacturer = elevatorinfo.manufacturer;
                            liftState.ThroughDoor = elevatorinfo.throughDoor;
                            liftState.physicalNumber = elevatorinfo.physicalNumber;
                            liftState.certificateNumber = elevatorinfo.certificateNumber;
                            liftState.regNumber = elevatorinfo.regNumber;
                            liftState.mainAreaId = elevatorinfo.mainAreaId;
                            liftState.mainAreaName = elevatorinfo.mainAreaName;
                            liftState.elevatorType = elevatorinfo.elevatorType;
                            liftState.FloorInf = elevatorinfo.floorInf;
                            liftState.ZLX = elevatorinfo.ZLX;
                            liftState.ZLY = elevatorinfo.ZLY;

                            #region 电梯状态解析
                            if (liftState.ThroughDoor == 1)
                            {
                                if (liftState.Car_door.Length == 2)
                                {
                                    int A_value = Convert.ToInt32(liftState.Car_door.Substring(0, 1));
                                    int B_value = Convert.ToInt32(liftState.Car_door.Substring(1, 1));
                                    if (A_value < 0 || A_value > 3 || B_value < 0 || B_value > 3)
                                    {
                                        liftState.Car_door = "11";
                                    }
                                    else
                                    {
                                        string doorstate = "";
                                        if (A_value == 0 || A_value == 1)
                                        {
                                            doorstate += "0";
                                        }
                                        if (A_value == 2 || A_value == 3)
                                        {
                                            doorstate += "1";
                                        }
                                        if (B_value == 0 || B_value == 1)
                                        {
                                            doorstate += "0";
                                        }
                                        if (B_value == 2 || B_value == 3)
                                        {
                                            doorstate += "1";
                                        }
                                        liftState.Car_door = doorstate;
                                    }
                                }
                                else
                                {
                                    liftState.Car_door = "11";
                                }
                            }
                            else
                            {
                                string door_value = liftState.Car_door.Substring(0, 1);
                                if (door_value == "0" || door_value == "1")
                                {
                                    liftState.Car_door = "0";
                                }
                                else if (door_value == "2" || door_value == "3")
                                {
                                    liftState.Car_door = "1";
                                }
                                else
                                {
                                    liftState.Car_door = "1";
                                }
                            }
                            if (liftState.Elevator_running_state > 6)
                            {
                                liftState.Elevator_running_state = 1;
                            }
                            string[] array = elevatorinfo.floorInf.Split(',');
                            if (array.Length < liftState.Car_position_index || liftState.Car_position_index < 1)
                            {
                                liftState.Car_position = "0";
                            }
                            else
                            {
                                if (liftState.Car_position_index > 0)
                                {
                                    int index = liftState.Car_position_index - 1;
                                    liftState.Car_position = array[index];
                                }
                                else
                                {
                                    liftState.Car_position = "0";
                                }
                            }
                            #endregion
                            //以上为电梯状态解析

                            //判断状态列表是否有状态
                            int ele_index = state_list.FindIndex(x => x.opcNO == liftState.opcNO);
                            if (ele_index > -1)
                            {
                                LiftStateALL liftState_old = new LiftStateALL();
                                liftState_old = state_list[ele_index];
                                liftState.maintenanceTime = liftState_old.maintenanceTime;
                                liftState.lastmaintenanceTime = liftState_old.lastmaintenanceTime;
                                liftState.nextmaintenanceTime = liftState_old.nextmaintenanceTime;
                                liftState.faultnum = liftState_old.faultnum;
                                if (liftState_old.Elevator_moving_status == liftState.Elevator_moving_status)
                                {
                                    liftState.StatusChange = 0;
                                }
                                else
                                {
                                    liftState.StatusChange = 1;
                                }
                                //统计开关门次数

                                if (liftState.Car_door != liftState_old.Car_door)
                                {
                                    liftState.OpenTime = liftState_old.OpenTime + 1;
                                }
                                else
                                {
                                    liftState.OpenTime = liftState_old.OpenTime;
                                }

                                //统计运行次数、时间
                                if (liftState_old.Moving_direction != liftState.Moving_direction)
                                {
                                    try
                                    {
                                        if (liftState_old.Moving_direction == 2)
                                        {
                                            liftState.StartTime = DateTime.Now;
                                            liftState.Runs = liftState_old.Runs;
                                            liftState.RunTimeSecond = liftState_old.RunTimeSecond;
                                            liftState.RunTime = Math.Round((double)liftState.RunTimeSecond / 3600, 4);
                                            liftState.bend = liftState_old.bend;
                                        }
                                        else if (liftState.Moving_direction == 2)
                                        {
                                            TimeSpan secondSpan = new TimeSpan(DateTime.Now.Ticks - liftState_old.StartTime.Ticks);
                                            int time = Convert.ToInt32(secondSpan.Seconds);
                                            if (time > 0)
                                            {
                                                int run_index = runtime_list.FindIndex(k => k.elevatorId == elevatorinfo.id && Convert.ToDateTime(k.runDate).Date == DateTime.Now.Date);
                                                if (run_index > -1)
                                                {
                                                    ElevatorStateRunTime elevatorStateRun = runtime_list[run_index];
                                                    elevatorStateRun.runTime = elevatorStateRun.runTime + time;
                                                    elevatorStateRun.runDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    runtime_list[run_index] = elevatorStateRun;
                                                    liftState.RunTimeSecond = liftState_old.RunTimeSecond + time;
                                                    liftState.RunTime = Math.Round((double)liftState.RunTimeSecond / 3600, 4);
                                                }
                                                else
                                                {
                                                    ElevatorStateRunTime elevatorStateRun = new ElevatorStateRunTime();
                                                    elevatorStateRun.elevatorId = elevatorinfo.id;
                                                    elevatorStateRun.runTime = time;
                                                    elevatorStateRun.runDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    runtime_list.Add(elevatorStateRun);
                                                    liftState.RunTimeSecond = liftState_old.RunTimeSecond + time;
                                                    liftState.RunTime = Math.Round((double)liftState.RunTimeSecond / 3600, 4);
                                                }

                                                int runs_index = run_list.FindIndex(k => k.elevatorId == elevatorinfo.id && Convert.ToDateTime(k.runsDate).Date == DateTime.Now.Date);
                                                if (runs_index > -1)
                                                {
                                                    ElevatorStateRun elevatorStateRun = run_list[runs_index];
                                                    elevatorStateRun.runs = elevatorStateRun.runs + 1;
                                                    elevatorStateRun.runsDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    run_list[runs_index] = elevatorStateRun;
                                                    liftState.Runs = liftState_old.Runs + 1;
                                                }
                                                else
                                                {
                                                    ElevatorStateRun elevatorStateRun = new ElevatorStateRun();
                                                    elevatorStateRun.elevatorId = elevatorinfo.id;
                                                    elevatorStateRun.runs = 1;
                                                    elevatorStateRun.runsDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                                    run_list.Add(elevatorStateRun);
                                                    liftState.Runs = liftState_old.Runs + 1;
                                                }
                                                liftState.bend = liftState_old.bend + 1;
                                            }
                                            else
                                            {
                                                liftState.Runs = liftState_old.Runs;
                                                liftState.bend = liftState_old.bend;
                                                liftState.RunTimeSecond = liftState_old.RunTimeSecond;
                                                liftState.RunTime = Math.Round((double)liftState_old.RunTimeSecond / 3600, 4);
                                            }
                                        }
                                        else
                                        {
                                            liftState.bend = liftState_old.bend;
                                            liftState.Runs = liftState_old.Runs;
                                            liftState.RunTimeSecond = liftState_old.RunTimeSecond;
                                            liftState.RunTime = Math.Round((double)liftState_old.RunTimeSecond / 3600, 4);
                                        }

                                        liftState.Startfloor = liftState_old.Startfloor;
                                        liftState.faultnum = liftState_old.faultnum;
                                    }
                                    catch
                                    {

                                    }
                                }
                                else
                                {
                                    liftState.Runs = liftState_old.Runs;
                                    liftState.RunTimeSecond = liftState_old.RunTimeSecond;
                                    liftState.RunTime = Math.Round((double)liftState_old.RunTimeSecond / 3600, 4);
                                    liftState.bend = liftState_old.bend;
                                }
                                //故障修复
                                if (liftState_old.Elevator_moving_status != 2 && liftState.Elevator_moving_status == 2)
                                {
                                    ElevatorAreaDAL da = new ElevatorAreaDAL();
                                    da.UpdateFaultTime(elevatorinfo.id);
                                    InitWorkOrder();
                                    bool result_5 = PushNoticeMessage("Refresh").Result;
                                    bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
                                    bool result3 = PushPromptMessage("PromptRefresh").Result;

                                    try
                                    {
                                        MqttDataDAL mqttDataDAL = new MqttDataDAL();
                                        List<FaultRecordReport> list = mqttDataDAL.QueryFaultRecordReport(elevatorinfo.elevatorNO, elevatorinfo.opcNO);
                                        foreach (var item in list)
                                        {
                                            DeviceFaultData deviceFaultData = new DeviceFaultData();
                                            deviceFaultData.alarmCode = "PSC-" + item.id;
                                            deviceFaultData.assetCode = "PSC-" + elevatorinfo.elevatorNO;
                                            deviceFaultData.assetName = elevatorinfo.elevatorName;
                                            deviceFaultData.content = elevatorinfo.mainAreaName + "-" + elevatorinfo.areaName + ";" + elevatorinfo.elevatorName + ";" + item.faultContent;
                                            deviceFaultData.alarmFixTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            deviceFaultData.alarmLastTime = item.faultTime == null ? "" : Convert.ToDateTime(item.faultTime).ToString("yyyy-MM-dd HH:mm:ss");
                                            deviceFaultData.alarmLevel = "urgentAlarm";
                                            deviceFaultData.alarmStatus = "FIXED";
                                            deviceFaultData.alarmSource = "SUB_SYSTEM_ALARM";
                                            PushPanoramicData(deviceFaultData);
                                        }
                                    }
                                    catch (Exception ex)
                                    {

                                    }
                                }

                                state_list[ele_index] = liftState;
                            }
                            else
                            {
                                liftState.StatusChange = 1;
                                liftState.maintenanceTime = elevatorinfo.maintenanceTime;
                                liftState.lastmaintenanceTime = elevatorinfo.lastmaintenanceTime;
                                liftState.nextmaintenanceTime = elevatorinfo.nextmaintenanceTime;
                                liftState.faultnum = elevatorinfo.faultnum;
                                liftState.Runs = elevatorinfo.Runs;
                                liftState.RunTimeSecond = elevatorinfo.RunTimeSecond;
                                liftState.RunTime = Math.Round((double)elevatorinfo.RunTimeSecond / 3600, 4);
                                liftState.RunTimeSecondSum = elevatorinfo.RunTimeSecond;
                                liftState.RunTimeSum = Math.Round((double)elevatorinfo.RunTimeSecond / 3600, 4);
                                liftState.StartTime = DateTime.Now;
                                liftState.runssum = elevatorinfo.runssum;
                                liftState.bend = elevatorinfo.bend;
                                liftState.OpenTime = elevatorinfo.runtimesum;
                                state_list.Add(liftState);
                            }
                            outstate = liftState;
                        }
                        else
                        {
                            outstate = null;
                            return message;
                        }
                    }
                    else
                    {
                        message.errcode = 1;
                        outstate = null;
                    }
                }
                else
                {
                    message.errcode = 1;
                    outstate = null;
                }

            }
            catch (Exception ex)
            {
                LogHelper.Log("数据处理异常" + ex.ToString());
                message.errcode = 1;
                outstate = null;
            }

            return message;
        }

        public static async Task<bool> PushPromptMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushPromptMessage(message);
        }

        public static void InitWorkOrder()
        {
            try
            {
                MqttDataDAL mqttDataDAL = new MqttDataDAL();
                int fault = 0;
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        string type = string.Empty;
                        int datanum = 0;

                        mqttdata mqttdata = new mqttdata();
                        if (i == 0)
                        {
                            type = "faultTotal";
                            List<mqttdata> list = mqttDataDAL.QueryMqttdata("OrderIncomplete", "04", "KONE");
                            int old_value = list.FirstOrDefault(x => x.dataType == "fault").dataNum;
                            datanum = old_value + mqttDataDAL.QueryTodayFault();
                            fault = datanum;
                        }
                        else if (i == 1)
                        {
                            type = "faultCompleted";
                            datanum = fault - mqttDataDAL.QueryInCompletelFault();
                        }

                        mqttdata.dataNum = datanum;
                        mqttdata.manufacturer = "KONE";
                        mqttdata.manufacturerId = "04";
                        mqttdata.topicType = "TodayProcess";
                        mqttdata.dataType = type;
                        bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                        if (result)
                        {
                            mqttDataDAL.UpdateMqttData(mqttdata);
                        }
                        else
                        {
                            mqttDataDAL.AddMqttData(mqttdata);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化工单数量";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化工单数量" + e.ToString());
            }
        }

        public List<ElevatorState> GetData()
        {
            List<ElevatorState> list = new List<ElevatorState>();
            try
            {
                LogHelper.Log("查询所有电梯状态数据：" + state_list.Count.ToString());
                Elevator elevator = new Elevator();

                if (device_list != null)
                {
                    foreach (var item in device_list)
                    {
                        ElevatorState elevatorState = new ElevatorState();
                        if (state_list.Count > 0)
                        {
                            int ele_index = state_list.FindIndex(x => x.opcNO == item.opcNO);
                            if (ele_index > -1)
                            {
                                LiftStateALL liftStateALL = new LiftStateALL();

                                liftStateALL = state_list[ele_index];
                                elevatorState.Alarm_bell = liftStateALL.Alarm_bell;
                                elevatorState.opcNO = liftStateALL.opcNO;
                                elevatorState.Areaname = liftStateALL.Areaname;
                                elevatorState.CarCall = liftStateALL.CarCall;
                                elevatorState.Car_door = liftStateALL.Car_door;
                                elevatorState.Car_load = liftStateALL.Car_load;
                                elevatorState.ElevatorID = liftStateALL.ElevatorID;
                                elevatorState.ElevatorNO = liftStateALL.ElevatorNO;
                                elevatorState.ElevatorName = liftStateALL.ElevatorName;
                                elevatorState.Elevator_control_status = liftStateALL.Elevator_control_status;
                                elevatorState.Elevator_moving_status = liftStateALL.Elevator_moving_status;
                                elevatorState.Elevator_running_state = liftStateALL.Elevator_running_state;
                                elevatorState.Faults = liftStateALL.Faults;
                                elevatorState.GroupID = liftStateALL.GroupID;
                                elevatorState.Landing_call_respond_down = liftStateALL.Landing_call_respond_down;
                                elevatorState.Landing_call_respond_up = liftStateALL.Landing_call_respond_up;
                                elevatorState.Full_load_alarm = liftStateALL.Full_load_alarm;
                                elevatorState.Moving_direction = liftStateALL.Moving_direction;
                                elevatorState.AreaID = liftStateALL.AreaID;
                                elevatorState.Car_position_index = liftStateALL.Car_position_index;
                                elevatorState.Car_position = liftStateALL.Car_position;
                                elevatorState.Outofservice = Convert.ToInt32(item.outofservice);
                                elevatorState.Elevator_control_statusName = liftStateALL.Elevator_control_statusName;
                                elevatorState.Manufacturer = liftStateALL.Manufacturer;
                                elevatorState.Model = liftStateALL.Model;
                                elevatorState.regNumber = liftStateALL.regNumber;
                                elevatorState.certificateNumber = liftStateALL.certificateNumber;
                                elevatorState.physicalNumber = liftStateALL.physicalNumber;
                                elevatorState.mainAreaId = liftStateALL.mainAreaId;
                                elevatorState.mainAreaName = item.mainAreaName;
                                elevatorState.Areaname = item.areaName;
                                elevatorState.cameraNo = item.cameraNo;
                                elevatorState.Elevator_control_statusNameEn = liftStateALL.Elevator_control_statusNameEn;
                                elevatorState.ZLY = liftStateALL.ZLY;
                                elevatorState.ZLX = liftStateALL.ZLX;
                                elevatorState.runssum = liftStateALL.runssum;
                                list.Add(elevatorState);
                            }
                            else
                            {
                                //LogHelper.Log("未找到" + item.opcNO + "电梯数据,数据总和" + state_list.Count.ToString());
                                elevatorState.Alarm_bell = 0;
                                elevatorState.opcNO = item.opcNO;
                                elevatorState.Areaname = item.areaName;
                                elevatorState.AreaID = item.areaId;
                                elevatorState.CarCall = "0000000000";
                                elevatorState.Car_door = "1";
                                elevatorState.Car_load = 0;
                                elevatorState.Car_position = string.IsNullOrEmpty(item.floorInf) ? "0" : item.floorInf.Split(',')[0].ToString();
                                elevatorState.ElevatorID = item.id;
                                elevatorState.ElevatorNO = item.elevatorNO;
                                elevatorState.ElevatorName = item.elevatorName;
                                elevatorState.Elevator_control_status = 99;
                                elevatorState.Elevator_running_state = 1;
                                elevatorState.Elevator_moving_status = 1;
                                elevatorState.Faults = 0;
                                elevatorState.GroupID = item.groupId;
                                elevatorState.Landing_call_respond_down = "0000000000";
                                elevatorState.Landing_call_respond_up = "0000000000";
                                elevatorState.Full_load_alarm = 0;
                                elevatorState.Moving_direction = 2;
                                elevatorState.Car_position_index = 1;
                                elevatorState.Outofservice = Convert.ToInt32(item.outofservice);
                                elevatorState.Elevator_control_statusName = "离线";
                                elevatorState.Elevator_control_statusNameEn = "OFL";
                                elevatorState.Manufacturer = item.manufacturer;
                                elevatorState.Model = item.model;
                                elevatorState.regNumber = item.regNumber;
                                elevatorState.certificateNumber = item.certificateNumber;
                                elevatorState.physicalNumber = item.physicalNumber;
                                elevatorState.mainAreaId = item.mainAreaId;
                                elevatorState.mainAreaName = item.mainAreaName;
                                elevatorState.Areaname = item.areaName;
                                elevatorState.cameraNo = item.cameraNo;
                                elevatorState.ZLX = item.ZLX;
                                elevatorState.ZLY = item.ZLY;
                                elevatorState.runssum = item.runssum;
                                list.Add(elevatorState);
                            }
                        }
                        else
                        {
                            //LogHelper.Log("所有电梯数据为0");
                            elevatorState.Alarm_bell = 0;
                            elevatorState.opcNO = item.opcNO;
                            elevatorState.Areaname = item.areaName;
                            elevatorState.AreaID = item.areaId;
                            elevatorState.CarCall = "0000000000";
                            elevatorState.Car_door = "1";
                            elevatorState.Car_load = 0;
                            elevatorState.Car_position = string.IsNullOrEmpty(item.floorInf) ? "0" : item.floorInf.Split(',')[0].ToString();
                            elevatorState.ElevatorID = item.id;
                            elevatorState.ElevatorNO = item.elevatorNO;
                            elevatorState.ElevatorName = item.elevatorName;
                            elevatorState.Elevator_control_status = 99;
                            elevatorState.Elevator_moving_status = 1;
                            elevatorState.Elevator_running_state = 1;
                            elevatorState.Faults = 0;
                            elevatorState.GroupID = item.groupId;
                            elevatorState.Landing_call_respond_down = "0000000000";
                            elevatorState.Landing_call_respond_up = "0000000000";
                            elevatorState.Full_load_alarm = 0;
                            elevatorState.Moving_direction = 2;
                            elevatorState.Car_position_index = 1;
                            elevatorState.Outofservice = Convert.ToInt32(item.outofservice);
                            elevatorState.Elevator_control_statusName = "离线";
                            elevatorState.Elevator_control_statusNameEn = "OFL";
                            elevatorState.Manufacturer = item.manufacturer;
                            elevatorState.Model = item.model;
                            elevatorState.regNumber = item.regNumber;
                            elevatorState.certificateNumber = item.certificateNumber;
                            elevatorState.physicalNumber = item.physicalNumber;
                            elevatorState.mainAreaId = item.mainAreaId;
                            elevatorState.mainAreaName = item.mainAreaName;
                            elevatorState.Areaname = item.areaName;
                            elevatorState.cameraNo = item.cameraNo;
                            elevatorState.ZLX = item.ZLX;
                            elevatorState.ZLY = item.ZLY;
                            elevatorState.runssum = item.runssum;
                            list.Add(elevatorState);
                        }
                    }
                }
                return list;
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询所有电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询所有电梯状态" + e.ToString());
                return list;
            }
        }

        public void UpdateFloor(Elevator elevator)
        {
            int ele_index = state_list.FindIndex(x => x.opcNO == elevator.opcNO);
            if (ele_index > -1)
            {
                LiftStateALL liftStateALL = state_list[ele_index];
                string[] array = elevator.floorInf.Split(',');
                if (array.Length < liftStateALL.Car_position_index || liftStateALL.Car_position_index < 1)
                {
                    liftStateALL.Car_position = "0";
                }
                else
                {
                    if (liftStateALL.Car_position_index > 0)
                    {
                        int index = liftStateALL.Car_position_index - 1;
                        liftStateALL.Car_position = array[index];
                    }
                    else
                    {
                        liftStateALL.Car_position = "0";
                    }
                }
                state_list[ele_index] = liftStateALL;
            }
        }

        public int ConvertState(int status)
        {
            int name = 2;
            switch (status)
            {
                case 0:
                    name = 2;
                    break;
                case 1:
                    name = 4;
                    break;
                case 99:
                    name = 1;
                    break;
                case 2:
                    name = 3;
                    break;
                case 3:
                    name = 3;
                    break;
                case 4:
                    name = 4;
                    break;
                case 7:
                    name = 4;
                    break;
                case 8:
                    name = 4;
                    break;
                case 14:
                    name = 3;
                    break;
                case 15:
                    name = 2;
                    break;
                case 17:
                    name = 4;
                    break;
            }
            return name;
        }

        public LiftStateALL GetLiftStateDetail(int elevatorid)
        {
            LiftStateALL elevatorState = new LiftStateALL();
            ElevatorAreaDAL da = new ElevatorAreaDAL();
            try
            {
                Elevator elevator = da.LoadElevator(elevatorid);
                if (elevator != null)
                {
                    elevatorState.cameraNo = elevator.cameraNo;
                    elevatorState.bend = elevator.bend;
                    elevatorState.OpenTime = elevator.runtimesum;
                    elevatorState.regNumber = elevator.regNumber;
                    elevatorState.physicalNumber = elevator.physicalNumber;
                    elevatorState.Manufacturer = elevator.manufacturer;
                    elevatorState.elevatorType = elevator.elevatorType;
                    elevatorState.ElevatorID = elevator.id;
                    elevatorState.ElevatorNO = elevator.elevatorNO;
                    elevatorState.FloorInf = elevator.floorInf;
                    elevatorState.SaleNo = elevator.saleNo;
                    elevatorState.Speed = elevator.speed;
                    elevatorState.ContractNo = elevator.contractNo;
                    elevatorState.IPAddress = elevator.ipAddress;
                    elevatorState.ThroughDoor = elevator.throughDoor;
                    elevatorState.Areaname = elevator.areaName;
                    elevatorState.ElevatorName = elevator.elevatorName;
                    elevatorState.Outofservice = Convert.ToInt32(elevator.outofservice);
                    elevatorState.opcNO = elevator.opcNO;
                    elevatorState.GroupID = elevator.groupId;
                    elevatorState.mainAreaName = elevator.mainAreaName;
                    elevatorState.Model = elevator.model;
                    elevatorState.ZLX = elevator.ZLX;
                    elevatorState.ZLY = elevator.ZLY;
                    elevatorState.runssum = elevator.runssum;

                    int ele_index = state_list.FindIndex(x => x.opcNO == elevator.opcNO);
                    if (ele_index > -1)
                    {
                        LiftStateALL liftStateALL = new LiftStateALL();
                        liftStateALL = state_list[ele_index];
                        elevatorState.Alarm_bell = liftStateALL.Alarm_bell;
                        elevatorState.Areaname = liftStateALL.Areaname;
                        elevatorState.CarCall = liftStateALL.CarCall;
                        elevatorState.Car_door = liftStateALL.Car_door;
                        elevatorState.Car_load = liftStateALL.Car_load;
                        elevatorState.Car_position = liftStateALL.Car_position;
                        elevatorState.Elevator_control_status = liftStateALL.Elevator_control_status;
                        elevatorState.Elevator_moving_status = liftStateALL.Elevator_moving_status;
                        elevatorState.Faults = liftStateALL.Faults;
                        elevatorState.Landing_call_respond_down = liftStateALL.Landing_call_respond_down;
                        elevatorState.Landing_call_respond_up = liftStateALL.Landing_call_respond_up;
                        elevatorState.Full_load_alarm = liftStateALL.Full_load_alarm;
                        elevatorState.Moving_direction = liftStateALL.Moving_direction;
                        elevatorState.Car_position_index = liftStateALL.Car_position_index;
                        elevatorState.Elevator_running_state = liftStateALL.Elevator_running_state;
                        elevatorState.Elevator_control_statusName = liftStateALL.Elevator_control_statusName;
                        elevatorState.Elevator_control_statusNameEn = liftStateALL.Elevator_control_statusNameEn;
                        elevatorState.faultnum = liftStateALL.faultnum;
                        elevatorState.Runs = liftStateALL.Runs;
                        elevatorState.RunTimeSecond = liftStateALL.RunTimeSecond;
                        elevatorState.RunTime = Math.Round((double)elevatorState.RunTimeSecond / 3600, 4);
                        elevatorState.lastmaintenanceTime = liftStateALL.lastmaintenanceTime;
                        elevatorState.maintenanceTime = liftStateALL.maintenanceTime;
                        elevatorState.nextmaintenanceTime = liftStateALL.nextmaintenanceTime;
                        elevatorState.OpenTime = liftStateALL.OpenTime;
                    }
                    else
                    {
                        elevatorState.Alarm_bell = 0;
                        elevatorState.CarCall = "00000000000000000000000";
                        if (elevator.throughDoor == 1)
                        {
                            elevatorState.Car_door = "11";
                        }
                        else
                        {
                            elevatorState.Car_door = "1";
                        }
                        elevatorState.Car_load = 0;
                        elevatorState.Elevator_control_status = 99;
                        elevatorState.Elevator_moving_status = 1;
                        elevatorState.Elevator_running_state = 1;
                        elevatorState.Faults = 0;
                        elevatorState.Landing_call_respond_down = "00000000000000000000000";
                        elevatorState.Landing_call_respond_up = "00000000000000000000000";
                        elevatorState.Full_load_alarm = 0;
                        elevatorState.Moving_direction = 2;
                        elevatorState.Car_position_index = 1;
                        elevatorState.Car_position = string.IsNullOrEmpty(elevator.floorInf) ? "0" : elevator.floorInf.Split(',')[0];
                        elevatorState.Elevator_control_statusName = "离线";
                        elevatorState.Elevator_control_statusNameEn = "OFL";
                        elevatorState.lastmaintenanceTime = da.QuerylastMaintenance(elevatorid);
                        elevatorState.maintenanceTime = da.QuerylastRepairTime(elevatorid);
                        elevatorState.nextmaintenanceTime = da.QueryNextMaintenance(elevatorid);
                        elevatorState.faultnum = da.QueryElevatorFault(elevatorid);
                        elevatorState.Runs = da.QueryElevatorRuns(elevatorid);
                        elevatorState.RunTimeSecond = da.QueryElevatorRunTime(elevatorid);
                        elevatorState.RunTime = Math.Round((double)elevatorState.RunTimeSecond / 3600, 4);
                    }
                }
            }
            catch (Exception e)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "查询单台电梯状态";
                errorLogInfo.errorMsg = e.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("查询单台电梯状态" + e.ToString());
                return elevatorState;
            }
            return elevatorState;
        }

        public void MqttKoneDeviceSync(KoneDeviceStateSync koneDeviceStateSync)
        {
            try
            {
                LiftStateALL liftState = new LiftStateALL();
                liftState.opcNO = koneDeviceStateSync.opcNO;
                //liftState.Car_position = koneDeviceStateSync.Car_position.ToString();
                liftState.Car_door = koneDeviceStateSync.Car_door;
                liftState.Moving_direction = koneDeviceStateSync.Moving_direction;
                liftState.Elevator_control_status = koneDeviceStateSync.Elevator_control_status;
                liftState.Full_load_alarm = koneDeviceStateSync.Full_load_alarm;
                liftState.Car_load = koneDeviceStateSync.Car_load;
                liftState.CarCall = koneDeviceStateSync.CarCall;
                liftState.Landing_call_respond_up = koneDeviceStateSync.Landing_call_respond_up;
                liftState.Landing_call_respond_down = koneDeviceStateSync.Landing_call_respond_down;
                liftState.Faults = koneDeviceStateSync.Faults;
                liftState.Alarm_bell = koneDeviceStateSync.Alarm_bell;
                liftState.Elevator_running_state = koneDeviceStateSync.Elevator_running_state;
                liftState.Car_position_index = koneDeviceStateSync.Car_position;
                liftState.Elevator_control_statusName = ConvertStatuName(liftState.Elevator_control_status);
                liftState.Elevator_control_statusNameEn = ConvertStatuNameEn(liftState.Elevator_control_status);
                liftState.Elevator_moving_status = ConvertState(liftState.Elevator_control_status);
                liftState.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                LiftStateALL liftState2 = new LiftStateALL();
                //InsertData(koneDeviceStateSync.opcNO, liftState, out liftState2);
                ProcessData(liftState, out liftState2);
                if (liftState2 != null)
                {
                    if (liftState2.StatusChange == 1)
                    {
                        InitDevice();
                        bool result_5 = PushNoticeMessage("Refresh").Result;
                        bool result_6 = PushKoneHomeMessage("RefreshHomePage").Result;
                        bool result4 = PushElevatorListMessage("RefreshElevator").Result;
                    }
                    bool result2 = PushElevatorSingleMessage(liftState2.ElevatorID, liftState2).Result;
                }
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "电梯Mqtt数据处理";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("电梯数据处理" + ex.ToString());
            }
        }

        public async Task<bool> PushNoticeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushNoticeMessage(message);
        }

        public async Task<bool> PushKoneHomeMessage(string message)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushKoneHomeMessage(message);
        }

        public void KoneDeviceTemperature(KoneDeviceTemperature koneDeviceTemperature)
        {
            try
            {
                int ele_index = state_list.FindIndex(x => x.opcNO == koneDeviceTemperature.opcNO);
                if (ele_index > -1)
                {
                    LiftStateALL liftStateALL = state_list[ele_index];
                    //LogHelper.Log("温度：data:" + JsonConvert.SerializeObject(liftStateALL));
                    liftStateALL.Temperature = koneDeviceTemperature.temperaturevalue;
                    //LogHelper.Log("温度：前前前：总数据量" + state_list.Count + "," + koneDeviceTemperature.opcNO + "," + ele_index + "," + JsonConvert.SerializeObject(koneDeviceTemperature));
                    state_list[ele_index] = liftStateALL;
                    //LogHelper.Log("温度：后后后：总数据量" + state_list.Count + "," + koneDeviceTemperature.opcNO + ele_index + state_list[ele_index]);
                    bool result2 = PushElevatorSingleMessage(liftStateALL.ElevatorID, liftStateALL).Result;
                }
                //LiftStateALL liftStateALL = new LiftStateALL();

                //if (_dic.TryGetValue(koneDeviceTemperature.opcNO, out liftStateALL))
                //{
                //    liftStateALL.Temperature = koneDeviceTemperature.temperaturevalue;
                //    _dic.Remove(koneDeviceTemperature.opcNO);
                //    _dic.Add(koneDeviceTemperature.opcNO, liftStateALL);
                //    bool result2 = PushElevatorSingleMessage(liftStateALL.ElevatorID, liftStateALL).Result;
                //}
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "电梯温度数据处理";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("电梯温度数据处理" + ex.ToString());
            }
        }

        public void InitDevice()
        {
            try
            {
                //MqttDataDAL mqttDataDAL = new MqttDataDAL();

                List<ElevatorState> list = GetData();
                int maintenanceTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 4; }).Count;
                int faultTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 3; }).Count;
                int normalTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 2; }).Count;
                int offTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 1; }).Count;
                if (KoneDeviceStatus != null)
                {
                    int devicetotal = 0;
                    if (device_list != null)
                    {
                        devicetotal = device_list.Count;
                    }
                    KoneDeviceStatus.offlineTotal = offTotal;
                    KoneDeviceStatus.normalTotal = normalTotal;
                    KoneDeviceStatus.faultTotal = faultTotal;
                    KoneDeviceStatus.maintenanceTotal = maintenanceTotal;
                    KoneDeviceStatus.deviceTotal = devicetotal;
                }
                //for (int i = 0; i < 5; i++)
                //{
                //    try
                //    {
                //        string type = string.Empty;
                //        int datanum = 0;
                //        mqttdata mqttdata = new mqttdata();

                //        if (i == 0)
                //        {
                //            type = "normalTotal";
                //            datanum = normalTotal;
                //        }
                //        else if (i == 1)
                //        {
                //            type = "faultTotal";
                //            datanum = faultTotal;
                //        }
                //        else if (i == 2)
                //        {
                //            type = "maintenanceTotal";
                //            datanum = maintenanceTotal;
                //        }
                //        else if (i == 3)
                //        {
                //            type = "offlineTotal";
                //            datanum = offTotal;
                //        }
                //        else if (i == 4)
                //        {
                //            type = "deviceTotal";
                //            datanum = devicetotal;
                //        }
                //        mqttdata.dataNum = datanum;
                //        mqttdata.manufacturer = "KONE";
                //        mqttdata.manufacturerId = "04";
                //        mqttdata.topicType = "DeviceStatusTotal";
                //        mqttdata.dataType = type;
                //        //bool result = mqttDataDAL.CheckData(mqttdata.manufacturer, mqttdata.manufacturerId, type, mqttdata.topicType);

                //        //if (result)
                //        //{
                //        //    mqttDataDAL.UpdateMqttData(mqttdata);
                //        //}
                //        //else
                //        //{
                //        //    mqttDataDAL.AddMqttData(mqttdata);
                //        //}
                //    }
                //    catch
                //    {
                //        continue;
                //    }
                //}
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "初始化设备数量";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("初始化设备数量" + ex.ToString());
            }
        }

        public string ConvertStatuName(int status)
        {
            // string name = "OFL";
            string name = "在线";
            switch (status)
            {
                case 0:
                    //name = "NOR";
                    name = "正常";
                    break;
                case 1:
                    //name = "INS";
                    name = "检修";
                    break;
                case 99:
                    //name = "NOC";
                    name = "离线";
                    break;
                case 2:
                    //name = "FRD";
                    name = "消防";
                    break;
                case 3:
                    //name = "STP";
                    name = "安全回路";
                    break;
                case 4:
                    //name = "ATS";
                    name = "司机";
                    break;
                case 7:
                    //name = "OSS";
                    name = "锁梯";
                    break;
                case 8:
                    //name = "PRC";
                    name = "优先运行";
                    break;
                case 14:
                    //name = "EFA";
                    name = "故障";
                    break;
                case 15:
                    //name = "PAD";
                    name = "泊停";
                    break;
                case 17:
                    //name = "DIS";
                    name = "外呼关闭";
                    break;
            }
            return name;
        }

        public string ConvertStatuNameEn(int status)
        {
            string name = "NOR";
            switch (status)
            {
                case 0:
                    name = "NOR";
                    break;
                case 99:
                    name = "NOC";
                    break;
                case 1:
                    name = "INS";
                    break;
                case 2:
                    name = "FRD";
                    break;
                case 3:
                    name = "STP";
                    break;
                case 4:
                    name = "ATS";
                    break;
                case 7:
                    name = "OSS";
                    break;
                case 8:
                    name = "PRC";
                    break;
                case 14:
                    name = "EFA";
                    break;
                case 15:
                    name = "PAD";
                    break;
                case 17:
                    name = "DIS";
                    break;
            }
            return name;
        }

        public async Task<bool> PushElevatorSingleMessage(int elevatorid, LiftStateALL liftState)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushElevatorMessage(elevatorid, liftState);
        }

        public async Task<bool> PushElevatorListMessage(string msg)
        {
            return await ElevatorWebSocketMiddleware.webSocketManage.PushElevatorListMessage(msg);
        }

        public void UpdateData(string opcNo, LiftStateALL liftStateALL)
        {
            try
            {
                int ele_index = state_list.FindIndex(x => x.opcNO == opcNo);
                if (ele_index > -1)
                {
                    //LogHelper.Log("更新状态：" + JsonConvert.SerializeObject(liftStateALL));
                    //LogHelper.Log("更新状态前前前：" + JsonConvert.SerializeObject(state_list[ele_index]) + "," + opcNo + "," + ele_index);
                    state_list[ele_index] = liftStateALL;
                    //LogHelper.Log("更新状态后后后：" + JsonConvert.SerializeObject(state_list[ele_index]));
                    UpdateDeviceStatus();
                }
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "更新电梯状态信息";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("更新电梯状态信息" + ex.ToString());
            }
        }

        public void UpdateDeviceStatus()
        {
            try
            {
                List<ElevatorState> list = GetData();
                int maintenanceTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 4; }).Count;
                int faultTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 3; }).Count;
                int normalTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 2; }).Count;
                int offTotal = list.FindAll(delegate (ElevatorState e) { return e.Elevator_moving_status == 1; }).Count;
                if (KoneDeviceStatus != null)
                {
                    int devicetotal = 0;
                    if (device_list != null)
                    {
                        devicetotal = device_list.Count;
                    }
                    KoneDeviceStatus.offlineTotal = offTotal;
                    KoneDeviceStatus.normalTotal = normalTotal;
                    KoneDeviceStatus.faultTotal = faultTotal;
                    KoneDeviceStatus.maintenanceTotal = maintenanceTotal;
                    KoneDeviceStatus.deviceTotal = devicetotal;
                }
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "更新设备状态信息";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("更新设备状态信息" + ex.ToString());
            }
        }

        public void RemoveRunsData(int elevatorid, DateTime date)
        {
            int data_id = run_list.FindIndex(x => x.elevatorId == elevatorid && Convert.ToDateTime(x.runsDate).Date == date.Date);
            if (data_id > -1)
            {
                ElevatorStateRun elevatorStateRun = run_list[data_id];
                run_list.Remove(elevatorStateRun);
            }
        }

        public void RemoveRunTimeData(int elevatorid, DateTime date)
        {
            int data_id = runtime_list.FindIndex(x => x.elevatorId == elevatorid && Convert.ToDateTime(x.runDate).Date == date.Date);
            if (data_id > -1)
            {
                ElevatorStateRunTime elevatorStateRun = runtime_list[data_id];
                runtime_list.Remove(elevatorStateRun);
            }
        }

        public void PushPanoramicData(DeviceFaultData deviceFaultData)
        {
            var message = new NewLife.RocketMQ.Protocol.Message()
            {
                BodyString = JsonConvert.SerializeObject(deviceFaultData),
                Flag = 0,
                WaitStoreMsgOK = true
            };
            //发送消息（生产消息）
            var sr = FXMQClient.Producer.Publish(message);
            FXMQClient.Producer.Dispose();
        }

        public void ClearBend(string opcNo)
        {
            try
            {
                int ele_index = state_list.FindIndex(x => x.opcNO == opcNo);
                if (ele_index > -1)
                {
                    LiftStateALL liftStateALL = new LiftStateALL();
                    liftStateALL = state_list[ele_index];
                    liftStateALL.bend = 0;
                    state_list[ele_index] = liftStateALL;
                }
            }
            catch (Exception ex)
            {
                LogBUS logBUS = new LogBUS();
                ErrorLogInfo errorLogInfo = new ErrorLogInfo();
                errorLogInfo.operation = "更新电梯状态信息";
                errorLogInfo.errorMsg = ex.ToString();
                logBUS.InsertErrorLog(errorLogInfo);
                LogHelper.Log("更新电梯状态信息" + ex.ToString());
            }
        }
    }
}